package com.tc.security01.config;

import com.tc.security01.config.filter.LimitFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.session.SessionInformationExpiredEvent;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletResponse;


/**
 * @Auther: tianchao
 * @Date: 2021/10/24 12:18
 * @Description:
 */
@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/customerLogin.html")
                .loginProcessingUrl("/user/login")
                .defaultSuccessUrl("/main.html");
                //.failureForwardUrl("/login-error.html");
        http.addFilterAfter(limitFiler(), SecurityContextPersistenceFilter.class);
        http.sessionManagement().invalidSessionUrl("/moreTime.html").maximumSessions(1).maxSessionsPreventsLogin(false)
                .expiredSessionStrategy((event)->{
                    HttpServletResponse response = event.getResponse();
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write("您已经被挤兑下线");
                });
        http.authorizeRequests().antMatchers("/kk-anti-reptile/refresh","/kk-anti-reptile/validate","/customerLogin.html","/user/login","/moreTime.html","/demo/hello").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
        http.csrf().disable();
        //super.configure(http);
    }
    @Bean
    public Filter limitFiler(){
        return new LimitFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
